package com.vip.websocket.controller;

import com.vip.websocket.service.WebSocketServer;
import com.vip.websocket.utils.IPUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * WebSocket Controller
 *
 * @author wgb
 * @date 2024/06/06
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/ws")
@RequiredArgsConstructor
public class WebSocketController {

    private final WebSocketServer webSocketServer;

    /**
     * 发送消息到指定用户
     *
     * @param message  消息
     * @param toUserId 目标用户ID
     * @param request  请求
     * @return {@link ResponseEntity}<{@link String}>
     */
    @GetMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToUser(String message, @PathVariable String toUserId, HttpServletRequest request) {
        webSocketServer.sendToUser(String.format("C1L2I3E4N5T_^Ag5F_%s_^Ag5F_私信：%s", IPUtils.getIpAddr(request), message), toUserId);
        return ResponseEntity.ok("消息发送成功");
    }

    /**
     * 群发消息
     *
     * @param message 消息
     * @param request 请求
     * @return {@link ResponseEntity}<{@link String}>
     */
    @GetMapping("/push")
    public ResponseEntity<String> pushToWeb(String message, HttpServletRequest request) {
        webSocketServer.sendToAll(String.format("C1L2I3E4N5T_^Ag5F_%s_^Ag5F_%s", IPUtils.getIpAddr(request), message));
        return ResponseEntity.ok("群发消息成功");
    }
}
